import java.lang.IllegalThreadStateException;
import java.io.IOException;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
import java.util.EventListener;
import java.util.Map;
import java.util.Vector;

public class ServiceSocket extends Thread implements Runnable
{
	// Server
	private ServerSocket listener;
	private Socket socket;
	private int port = 4444, maxConnections = 0;
	private Vector<ServiceThread> threads = new Vector(5, 5);
	public String name = "ServiceSocket";

	// instance
	private AMFServer server;
	
	ServiceSocket ()
	{
		this.server = AMFServer.getInstance();
	}
	
	public void run()
	{
		server.out("Server Started ...");
		maxConnections = 0;
		int i = 0;

		try {
			listener = new ServerSocket(port);
		
			while ( ((i++ < maxConnections) || (maxConnections == 0))) {
				socket = listener.accept();
				ServiceThread st = new ServiceThread(socket);
				st.start();
				threads.addElement(st);
			}
		} catch (IOException ioe) {
//			System.out.println("IOException on socket listen: " + ioe);
//			ioe.printStackTrace();
		} catch (IllegalThreadStateException ilt ) {
			System.out.println("IllegalThreadStateException on socket listen: " + ilt);
		} finally {
			server.out("Server Stopped ...");
		}
	}
	
	public void startServer()
	{
		this.start();
	}
	
	public void stopServer()
	{
		try {
			Enumeration tmpt = threads.elements();
	        while (tmpt.hasMoreElements())
	        {
	        	ServiceThread st = (ServiceThread)tmpt.nextElement();
	            st.stopSocket();
	        } 
			
	        this.interrupt();
			listener.close();
			
		} catch (SecurityException se) {
			
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	

}
